<script setup lang='ts'>
import { appRef } from '@/models/app.ref';
import { onMounted, ref } from 'vue';
import Sider from '@/components/chat/Sider.vue'
import Interactive from '@/components/chat/Interactive.vue'
import Explanation from '@/components/Explanation.vue';
import MdEditor from '@/components/MdEditor.vue';
import VTT from '@/components/VTT.vue'
import UploadFile from '@/components/chat/UploadFile.vue'
import { workService } from '@/services/work.service';
import { ChatWorkMenuInfo, ChatWorkModelInfo } from '@/models/chat-work';
import { SiderMenuEnum } from '@/models/@types';
import { shareService } from '@/services/share.service';
import { clipboardWriteText, getUuid } from '@/utils/common.methods';
import { Message } from '@arco-design/web-vue';
import { appContext } from '@/models/app.context';
import { PromptInfo } from '@/models/prompt';
import { matchHotKey } from "vditor/dist/ts/util/hotKey";


const isMobil = ref(false);
const menus = ref([]);
const currMenu = ref({} as ChatWorkMenuInfo);
const currPrompt = ref({} as PromptInfo);
const loading = ref(true);
onMounted(async () => {
  isMobil.value = appContext.system.data.viewWidth < 1000;
  await init();
  getModels();
  const sessions = currMenu.value?.sessions;
  if (sessions?.length === 1) {
    sendMessage('', sessions[0].uid, true);
  }
})

async function getModels(): Promise<void> {
  loading.value = true;
  await workService.getModelList();
  loading.value = false;
}

function getModel(value: string): ChatWorkModelInfo {
  return appRef.chatWork.models?.find(val => val.value === value);
}

async function init(): Promise<void> {
  menus.value = await appRef.chatWork.menus();
  currMenu.value = appRef.chatWork?.currMenu;
  currPrompt.value = await appRef.prompt.get(currMenu.value?.prompt) || {} as PromptInfo
}

async function onAdd(e: { type: SiderMenuEnum, parent?: string }): Promise<void> {
  const { type, parent } = e
  await appRef.chatWork.add(type, parent);
  init();
}

async function onItem(uid: string): Promise<void> {
  console.log('onItem', uid);
  await appRef.chatWork.setCurrKey(uid);
  init();
}

async function onEdit(param: { uid: string, label: string }): Promise<void> {
  const { uid, label } = param;
  await appRef.chatWork.edit(uid, label);
}

async function onPrompt(id: string): Promise<void> {
  await appRef.chatWork.updatedPrompt(currMenu.value.uid, id);
  init();
}

async function onUpdate(enmus: ChatWorkMenuInfo[]): Promise<void> {
  await appRef.chatWork.update(enmus)
  init();
}

const uploadFileRef = ref(null);
const controllerKey = getUuid();
const textarea = ref('');
const isSend = ref(false);
const chunk = ref('');

async function sendMessage(value: string = textarea.value, quote: string = undefined, auto: boolean = false): Promise<void> {
  if (isSend.value) return;
  if (!appRef.chatWork.models?.length) {
    await getModels();
  }
  if (!value && !auto) return;
  isSend.value = true;
  textarea.value = '';
  const files = uploadFileRef?.value?.getFiles() || [];
  workService.sendStream(controllerKey, value, files, currMenu.value?.continuous, ((data: string) => {
    chunk.value += data;
  }), callback, quote);
}

function callback() {
  isSend.value = false;
  chunk.value = '';
}

function stopSend() {
  workService.stopSend(controllerKey, callback);
}

function onRefresh(quote: string): void {
  const currSession = appRef.chatWork?.currMenu?.sessions?.find((val) => val.quote === quote);
  appRef.chatWork.removeMenuAnswer(currSession.uid, false);
  sendMessage(currSession.richtext, quote);
}

//下面代码是分享功能的代码
const popcontent = ref('');
const popvisible = ref(false);
const poptitle = ref("分享成功")
const checkboxes = ref([]);
const visible = ref(false);
const btnloading = ref(false);
const handleClick = () => {
  visible.value = true;
  checkboxes.value = appRef.chatWork.currMenu.sessions.map(() => false);
};

async function handleBeforeOk() {
  btnloading.value = true;
  const records = appRef.chatWork.currMenu.sessions.filter((_, index) => checkboxes.value[index]);
  if (records != null && records.length > 0) {
    var response = await shareService.send(records);
    if (response.status == true) {
      popcontent.value = window.location.href.replace("working-edition", "share") + '/' + response.uuid;
      popvisible.value = true;
      poptitle.value = "分享成功";
      visible.value = false;
      btnloading.value = false;
    } else {
      popcontent.value = response.error;
      popvisible.value = true;
      poptitle.value = "分享失败";
      visible.value = false;
      btnloading.value = false;
    }
  }
};
const popBeforeOk = (done) => {
  clipboardWriteText(popcontent.value).then(() => {
    Message.success('复制成功')
  })
  done();
};
const handleCancel = () => {
  visible.value = false;
}
// 复选框状态变化时触发
const handleCheckboxChange = (index) => {
  checkboxes.value[index] = !checkboxes.value[index];
};

function checkAll() {// 检查是否所有值都为true
  const allTrue = checkboxes.value.every(value => value === true);
  console.log(allTrue)
  // 遍历checkboxes中的值，根据条件进行更改
  checkboxes.value = checkboxes.value.map(() => allTrue ? false : true);
}


const isOptimize = ref(false);
const optimizeKey = getUuid();
function optimizePrompt() {
  if (isSend.value || !textarea.value || loading.value) return;
  let chunk = '';
  isOptimize.value = true
  workService.optimize(optimizeKey, textarea.value, data => {
    chunk += data
    textarea.value = chunk
  }, () => {
    textarea.value = chunk
    isOptimize.value = false
  })
}

const isMdEditor = ref(false);

</script>
<template>
  <div class="index">
    <a-layout style="height: 100%;">

      <a-layout>
        <div class="main flex" v-if="currMenu?.uid">
          <div class="content flex-c">
            <a-resize-box :directions="isMobil ? [] : ['bottom']" :style="{ minWidth: '100px', maxWidth: '100%' }">
              <Interactive :chunk="chunk" :sessions="currMenu?.sessions || []" v-if="currMenu?.uid"
                v-model:isSend="isSend" :isrefresh="true" @send="sendMessage" @refresh="onRefresh"
                @remove="appRef.chatWork.removeMenuAnswer($event)" @stopSend="stopSend" @prompt="onPrompt"
                @editTextarea="textarea = $event" :isPrompt="true" :prompt="currPrompt"
                :prologue="currPrompt?.workflow || currPrompt?.value">
                <template #select-model>
                  <a-select style="width: 120px" v-model="currMenu.modeluid" placeholder="请选择模型">
                    <a-option v-for="item in appRef.chatWork.models" :value="item.value" :label="item.label"></a-option>
                  </a-select>
                  <a-checkbox v-model="currMenu.continuous">长期记忆</a-checkbox>
                  <a-tooltip content="默认记忆近五轮对话内容，开启后，所有对话内容都将输入模型中(可能会导致超长报错)">
                    <icon-question-circle size="20" />
                  </a-tooltip>
                </template>
                <template #button-bar>
                  <a-button @click="handleClick" style="margin-right: 5px;" v-if="currMenu.sessions?.length">
                    <template #icon>
                      <icon-share-alt />
                    </template>
                    分享
                  </a-button>
                  <a-button @click="isMdEditor = !isMdEditor" style="margin-right: 5px;"
                    v-if="appContext.system.data.viewWidth > 1000">速记
                  </a-button>
                </template>
              </Interactive>
            </a-resize-box>

            <div class="text flex-c">
              <a-textarea class="textarea" v-model="textarea"
                :auto-size="isMobil ? { minRows: 2, maxRows: 15 } : { minRows: 2, maxRows: 500 }"
                placeholder="粘贴或输入你的需求，如: 请帮我看看文章有没有问题，附上文章的内容 （Ctrl + Enter = 发送，Enter = 换行）"
                @keydown.ctrl.enter="sendMessage(textarea)" />
              <a-space class="btns flex">
                <a-space class="left flex">
                  <div class="optimize flex" :style="{ opacity: (loading || !textarea || isOptimize) ? .7 : 1 }"
                    @click="optimizePrompt">
                    <img src="@/assets/icons/chat/optimize.png" :class="{ 'loading': isOptimize }">
                    {{ isOptimize ? "优化中" : "优化" }}
                  </div>

                </a-space>
                <a-space class="rigth flex">
                  <UploadFile ref="uploadFileRef" v-if="getModel(currMenu.modeluid)?.vision">
                    <icon-file size="25" />
                  </UploadFile>
                  <VTT @update:value="(value) => textarea += value" />
                  <a-button class="send" type="primary" :disabled="loading || !textarea"
                    @click.stop="sendMessage(textarea)" :loading="loading || isSend">
                    <template #icon>
                      <icon-send />
                    </template>
                    <template #default> {{ loading ? '模型加载中' : '发送' }}</template>
                  </a-button>
                </a-space>
              </a-space>
            </div>
          </div>
          <MdEditor :id="currMenu.uid" v-if="isMdEditor"></MdEditor>
        </div>
        <Explanation v-else />
      </a-layout>
      <Sider :menus="menus" :default-uid="currMenu?.uid" @add="onAdd"
        @clear="async () => { await appRef.chatWork.clear(); init() }" @click-item="onItem"
        @edit="($event) => { onEdit($event); init() }"
        @remove="async ($event) => { await appRef.chatWork.remove($event); init() }"
        @update="($event) => onUpdate($event)">
      </Sider>
    </a-layout>
    <a-modal v-model:visible="visible" title="分享" @cancel="handleCancel" @before-ok="handleBeforeOk" width="60vw"
      :fullscreen="appContext.system.data.viewWidth < 1000">
      <div style="max-height: 700px;overflow: auto;">
        <a-list>
          <a-list-item v-for="(item, index) in currMenu?.sessions" :key="item.uid" @click="handleCheckboxChange(index)">
            <a-checkbox :model-value="checkboxes[index]" :value="checkboxes[index]">
              <div class="ellipsis2">{{ item.richtext }}</div>
            </a-checkbox>
          </a-list-item>
        </a-list>
      </div>

      <template #footer>
        <a-button type="dashed" @click="handleCancel">取消</a-button>
        <a-button type="outline" @click="checkAll">全选</a-button>
        <a-button type="primary" @click="handleBeforeOk" :loading="btnloading">确定</a-button>
      </template>
    </a-modal>
    <a-modal v-model:visible="popvisible" :title="poptitle" okText="复制" @cancel="handleCancel" @before-ok="popBeforeOk">
      {{ popcontent }}
    </a-modal>
  </div>
</template>
<style lang='scss' scoped>
.index {
  height: 100%;

  .main {
    // max-width: 1270px;
    overflow: hidden;
    margin: 0 auto;
    justify-content: center;

    .content {
      max-width: 1270px;
      overflow: hidden;
      height: 100%;
      flex: 1;
    }

    @media screen and (max-width: 1200px) {
      .mask {
        display: none;
      }
    }
  }

  .text {
    width: 100%;
    position: relative;
    flex: 1;
    margin-bottom: 2px;

    @media screen and (min-width: 1000px) {
      max-height: calc(100% - 12px);
      min-height: 100px;
      overflow: auto;

      .textarea {
        overflow: auto;
      }
    }


    .textarea {
      height: 100%;
      resize: none;
      background-color: var(--color-fill-2);
      padding-bottom: 50px;
    }


    .btns {
      position: absolute;
      bottom: 10px;
      width: 100%;
      padding: 0 20px;
      justify-content: space-between;

      .left {
        .optimize {
          cursor: pointer;
          font-size: 12px;

          img {
            width: 20px;
            height: 20px;
            margin-right: 4px;
          }
        }
      }

    }
  }
}
</style>
